package com.example.bankseckill.controller;

import com.example.bankseckill.pojo.vo.EmailVo;
import com.example.bankseckill.pojo.vo.RespBean;
import com.example.bankseckill.utils.MailUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *  登录验证码
 *  author：lyj
 */
@Slf4j
@Api(tags = "验证码接口")
@RestController
@RequestMapping("/bank")
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MailUtils mailUtils;

    @ApiOperation(value = "登录验证码")
    @GetMapping(value = "/capthca",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");

        //-------------------生成验证码 begin --------------------------
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        //获取用户ip地址
        String remoteAddr = request.getRemoteAddr();
        System.out.println("ip为"+remoteAddr);
        //将验证码和ip地址存入redis
        redisTemplate.opsForValue().set(remoteAddr+":",text,300,TimeUnit.SECONDS);
        log.info("验证码内容：" + text);
        //将验证码放入session中
//        request.getSession().setAttribute("captcha", text);
        //根据文本内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片，格式jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //-------------------生成验证码 end ----------------------------
    }

    /**
     * 发送邮箱验证码 注册用户
     * @param email
     * @return
     */
    @ApiOperation(value = "注册账号验证码")
    @RequestMapping(value = "/mail",method = RequestMethod.POST)
    public RespBean mail(@RequestBody @Validated EmailVo email)
    {
        //模拟真实业务
        String code = (String) redisTemplate.opsForValue().get(email.getIdentitycard() + ":" + email.getEmail());
        if(!StringUtils.isEmpty(code))
        {
            return RespBean.success("验证码已经发送了,请耐心等待！");
        }
        //生产随机的四位验证码！！
        code = UUID.randomUUID().toString().substring(0,4);
        mailUtils.MailMessage(code,email.getEmail());
        redisTemplate.opsForValue().set(email.getIdentitycard() + ":" + email.getEmail(),code,5, TimeUnit.MINUTES);
        return RespBean.success("验证码发送成功");
    }
}
